package com.witmore.neutron.ai.web.apiv2.login;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jk.common.response.ResponseResult;
import com.jk.common.utils.PasswordUtil;
import com.witmore.neutron.ai.db.entity.UserDO;
import com.witmore.neutron.ai.db.mapper.UserMapper;
import com.witmore.neutron.ai.web.annotation.NoLoginRequired;
import com.witmore.neutron.ai.web.controller.vo.SendSmsParam;
import com.witmore.neutron.ai.web.controller.vo.SmsCodeLoginParam;
import com.witmore.neutron.ai.web.controller.vo.UserSession;
import com.witmore.neutron.ai.web.service.SmsService;
import com.witmore.neutron.ai.web.service.UserService;
import com.witmore.neutron.ai.web.service.impl.UserServiceImpl;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * V2 短信验证码登录控制器
 * Author: 豆子高
 * Date: 2025/12/19
 */
@NoLoginRequired
@Slf4j
@RestController
@RequestMapping("/v2/sms")
public class SmsLoginControllerV2 {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private SmsService smsService;
    @Autowired
    private UserService userService;

    /**
     * 发送短信验证码
     */
    @ResponseBody
    @PostMapping("/send-code")
    public ResponseResult<Void> sendSms(@RequestBody SendSmsParam param) {
        if (param == null || !StringUtils.hasText(param.getPhone())) {
            return ResponseResult.fail(400, "手机号不能为空");
        }

        // 简单的手机号格式验证
        if (!param.getPhone().matches("^1[3-9]\\d{9}$")) {
            return ResponseResult.fail(400, "手机号格式不正确");
        }

        boolean success = smsService.sendVerificationCode(param.getPhone());
        if (success) {
            return ResponseResult.success();
        } else {
            return ResponseResult.fail(500, "验证码发送失败，请稍后重试");
        }
    }

    /**
     * 手机验证码登录（支持自动注册）
     */
    @ResponseBody
    @PostMapping("/login")
    public ResponseResult<UserSession> smsLogin(@RequestBody SmsCodeLoginParam param, HttpServletResponse response) {
        if (param == null || !StringUtils.hasText(param.getPhone()) || !StringUtils.hasText(param.getCode())) {
            return ResponseResult.fail(400, "手机号或验证码不能为空");
        }

        // 验证验证码
        boolean codeValid = smsService.verifyCode(param.getPhone(), param.getCode());
        if (!codeValid) {
            return ResponseResult.fail(401, "验证码错误或已过期");
        }

        // 根据手机号查找用户
        UserDO userDO = userMapper.selectOne(new LambdaQueryWrapper<UserDO>()
                .eq(UserDO::getUserPhone, param.getPhone())
        );

        // 如果用户不存在，自动注册
        if (userDO == null) {
            userDO = new UserDO();
            userDO.setUserName(param.getPhone());
            userDO.setNickName("手机用户_" + param.getPhone());
            userDO.setUserPhone(param.getPhone());
            userDO.setPassword(PasswordUtil.hashPassword("123456")); // 默认密码123456
            userDO.setOrgName("默认组织");
            userDO = userService.createNewUserNormal(userDO);
            if (userDO == null) {
                return ResponseResult.fail(500, "自动注册失败，请稍后重试");
            }
        }
        return ResponseResult.success(userServiceImpl.setUserSession(userDO));
    }
}
